<?php

/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/**
 * Description of RssParser
 *
 * @author Dell
 */
class RssParser {

    //put your code here
    var $stringRss;
    const PREFIX = "http://www.mtv.fr";

    function __construct($xml) {
        $this->stringRss = $xml;
    }

    function parse($xpath) {
       /* $xml = new SimpleXMLElement($this->stringRss);
        /* On applique le xpath 
        $res = $xml->children();
        var_dump($res);
        while (list(, $node) = each($result)) {
            echo 'resultat : ', $node, "\n";
        }
        */
        $doc = new DOMDocument;

        $doc->preserveWhiteSpace = false;

        $doc->Load('http://www.mtv.fr/services/scenic/feeds/get/rss/mgid:hcx:content:mtv.fr:c75b32a0-a1c1-4ea5-9460-b42472f096d0/');

        $titles = $this->getNodeValues('//item/title', $doc);
        $descriptions = $this->getNodeValues('//item/description', $doc);
        $links = $this->getNodeValues('//item/link', $doc);
        $html = $this->displayBlocRss($titles, $descriptions, $links);
        echo $html;
    }
    
    private function getNodeValues($query, $document){

        $xpath = new DOMXPath($document);
        $entries = $xpath->query($query);
        $n = 0;
        foreach ($entries as $entry) {
            $nodeValues[$n++] = $entry->nodeValue;
        }
        return $nodeValues;
    }
    
    function displayBlocRss($titles, $descriptions, $links){
        $html   = "<div id ='blocRSS'>";
        $html   .= "<div  class ='blocRSSTitle'>Flux RSS</div>";
        
        for($n = 0; $n < count($titles); $n++){
            //retourne la balise img
            $img = $this->findSubStringImgTag($descriptions[$n]);
            $descriptions[$n] = substr($descriptions[$n], $img["position"]);
            
            //génération du html
            $html .= "<a href=\"javascript:ouvrirFenetre('".self::PREFIX.$links[$n]."')\">";
            $html .= "  <div class = 'rowRSS'>";
            $html .= "      <div class = 'rowRSSTitle'>".$titles[$n]."</div>";
            $html .= "      <div class = 'imgRowRss'>".$img["balise"]."</div>";
            $html .= "      <div class = 'descriptionRowRss'>".$descriptions[$n]."</div><br style='clear:both'/>";
            $html .= "  </div>";
            $html .= "</a>";
        }
        $html   .= "</div>";
        return $html;
    }
    
    private function findSubStringImgTag($string){
        $img["position"] = stripos($string, ">")+1;
        $img["balise"] = substr($string, 0, $img["position"]);
        return $img;
    }

}

?>
